<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\IndicatorsDailySummary;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class TeamController extends Controller
{
    public function list(Request $request)
    {
        $inviterType = $request->get('inviter_type', 'direct_inviter');
        return $this->response->array(
            Agent::query()
                ->with('wechat')
                ->withoutGlobalScope('orderByIdDesc')
                ->when($inviterType, function (Builder $builder, $inviterType) {
                    $builder
                        ->where('agents.' . $inviterType, $this->user->getKey())
                        ->when($inviterType === 'indirect_inviter', function (Builder $builder) {
                            $builder->with(['directInviter']);
                        });
                })
                ->when($request->get('search_name'), function (Builder $builder, $searchName) use ($inviterType) {
                    $builder
                        ->when($inviterType === 'indirect_inviter', function (Builder $builder) {
                            $builder->join('agents as direct_agent', 'direct_agent.id', '=', 'agents.direct_inviter');
                        })
                        ->where(function (Builder $builder) use ($searchName, $inviterType) {
                            $builder
                                ->when($inviterType === 'indirect_inviter', function (Builder $builder) use ($searchName) {
                                    $builder
                                        ->where('agents.name', 'like', "%$searchName%")
                                        ->orWhere('direct_agent.phone', 'like', "%$searchName%");
                                })
                                ->when($inviterType === 'direct_inviter', function (Builder $builder) use ($searchName) {
                                    $builder
                                        ->where('agents.name', 'like', "%$searchName%")
                                        ->orWhere('agents.phone', 'like', "%$searchName%");
                                });
                        });
                })
                ->when(
                    $request->get('performance_range_begin') && $request->get('performance_range_end'),
                    function (Builder $builder) use ($request) {
                        $begin = $request->get('performance_range_begin');
                        $end = $request->get('performance_range_end');

                        $builder
                            ->when($request->get('sort_by_performance', ''), function (Builder $builder, $orderType) {
                                $builder->orderBy('personal_performance', $orderType);
                            })
                            ->select([
                                // 这里把 personal_performance 和 team_performance 去掉, 单独另外统计
                                'agents.name', 'agents.phone', 'agents.level', 'agents.status', 'agents.created_at',
                                'agents.number_of_direct_inviter', 'agents.direct_inviter'
                            ])
                            ->selectSub(
                            // 个人业绩按日期范围汇总
                                \DB::table('indicators_daily_summary')
                                    ->selectRaw('sum(performance_summary)')
                                    ->whereBetween('day', [$begin, $end])
                                    ->where('type', IndicatorsDailySummary::TYPE_AGENT)
                                    ->whereRaw('agent_id = agents.id'),
                                'personal_performance'
                            )
                            ->selectSub(
                            // 团队业绩按日期范围汇总
                                \DB::table('indicators_daily_summary')
                                    ->selectRaw('sum(performance_summary)')
                                    ->whereBetween('day', [$begin, $end])
                                    ->where('type', IndicatorsDailySummary::TYPE_TEAM)
                                    ->whereRaw('agent_id = agents.id'),
                                'team_performance'
                            );
                    },
                    function (Builder $builder) use ($request) {
                        $builder
                            ->when($request->get('sort_by_performance', ''), function (Builder $builder, $orderType) {
                                $builder->orderBy('agents.personal_performance', $orderType);
                            })
                            ->select([
                                'agents.name', 'agents.phone', 'agents.level', 'agents.status', 'agents.created_at',
                                'agents.personal_performance', 'agents.team_performance', 'agents.number_of_direct_inviter',
                                'agents.direct_inviter'
                            ]);
                    })
                ->when($request->get('sort_by_created_at', ''), function (Builder $builder, $orderType) {
                    $builder->orderBy('agents.created_at', $orderType);
                })
                ->paginate()
        );
    }
}
